<template>
	<view class="index">
		<!-- <uni-nav-bar :fixed="true" :shadow="false" :statusBar="true" title=" " color="#000" backgroundColor="">
		</uni-nav-bar>
		<view :style="{height:`${configInfo.navBarHeight}px`}"></view> -->
		<view class="two-box">
			<view class="box-header flex-center pl-lg pr-lg f-title">
				<!-- <view @tap.stop="navSwitch(0)" class="pl-sm text-bold rel"
					:class="current == 0 ? 'c-title' : 'c-title-desc'">
					<text>账户登录</text>
					<text v-show="current == 0" class="nav-line abs" :style="{backgroundColor:primaryColor}"></text>
				</view> -->
				<view @tap.stop="navSwitch(1)" class="pr-sm text-bold rel"
					:class="current == 1 ? 'c-title' : 'c-title-desc'">
					<text>短信验证码登录</text>
					<!-- <text v-show="current == 1" class="nav-line abs" :style="{backgroundColor:primaryColor}"></text> -->
				</view>
			</view>
			<view class="pl-lg pr-lg box-item radius-16 flex-between">
				<view class="flex-y-center box-item-left">
					<view class="iconpingguoshouji_iphone_2x iconfont c-text"></view>
					<view class="pl-md c-title text-bold f-min-title">手机号</view>
				</view>
				<input type="text" class="flex-1 f-min-title" placeholder="请输入手机号" v-model="params.phone" />
			</view>
			<view class="pl-lg pr-lg box-item mt-lg radius-16 flex-between">
				<view class="flex-y-center box-item-left">
					<view class="icon-mima iconfont c-text"></view>
					<view class="pl-md c-title f-min-title  text-bold">验证码</view>
				</view>
				<input type="text" maxlength="6" class="flex-1 f-min-title" placeholder="请输入验证码"
					v-model="params.code" />
				<view @tap="getCode(1)" class="code-btn f-paragraph c-base radius-10 flex-center" 
				:style="{backgroundColor:primaryColor}">{{authTime?authTime:'获取验证码'}}</view>
			</view>
			<view class=" pt-lg flex-center pb-sm">
				<view class="flex pt-sm" @tap="isCheck = !isCheck ">
					<view class="pr-lg">
						<view class="icon-xuanze iconfont c-caption" v-if="!isCheck"></view>
						<view class="icon-xuanze-fill iconfont" v-else :style="{color:primaryColor}"></view>
					</view>
					<view class="f-caption box-text">
						<text>登录即表示您已详细阅读并同意</text>
						<text :style="{color:primaryColor}" @tap.stop="goDetail(2)">《服务协议》</text><text>与</text>
						<text :style="{color:primaryColor}" @tap.stop="goDetail(1)">《隐私协议》</text>
					</view>
				</view>
			</view>
			<view class="a-btn c-base f-title text-center radius-16 mb-lg mt-lg"
				:style="{backgroundColor:primaryColor,opacity: isCheck ? 1 : 0.3}" @tap="toLogin">
				{{current == 0 ? '登录' : '下一步'}}</view>
			<!-- <view class="text-right f-paragraph c-desc" @tap="$util.goUrl({url:`/login/pages/forgot-pwd`})">忘记密码?</view> -->
		</view>
		<pwPopup ref="pwpopup" :text="[{type:'close',text:'知道了'},{type:'confirm',text:'立即注册'}]" @confirm="confirm" @close="$refs.pwpopup.close()"
			content="你还没有注册或绑定微信哦!"></pwPopup>
			
		<uni-popup ref="show_apply" type="center" :maskClick="false">
			<view class="common-popup-content fill-base pd-lg radius-34 rel">
				<view class="title">温馨提示</view>
				<view class="f-title text-bold c-title mt-lg">
					暂未入驻
				</view>
				<view class="button">
					<view @tap.stop="toUrl(1)" class="item-child" :style="{background: primaryColor,color:'#fff'}">公司入驻
					</view>
					<view @tap.stop="toUrl(2)" class="item-child" :style="{background: primaryColor,color:'#fff'}">服务人员入驻
					</view>
				</view>
				<!-- <view class="button">
					<view @tap.stop="$refs.show_apply.close()" class="item-child">取消</view>
				</view> -->
				<view class="flex-center abs popup-close" @tap.stop="$refs.show_apply.close()">
					<i class="iconfont iconguanbi"></i>
				</view>
			</view>
		</uni-popup>
		
		<uni-popup ref="show_login" type="center" :maskClick="false">
			<view class="common-popup-content fill-base pd-lg radius-34 rel">
				<view class="title">温馨提示</view>
				<view class="f-title text-bold c-title mt-lg">
					原授权手机号{{coach_phone}}，是否换绑成新号{{params.phone}}
				</view>
				<view class="button">
					<view @tap.stop="replacePhone" :style="{background: primaryColor,color:'#fff'}" class="item-child">更换</view>
					<view @tap.stop="$util.goUrl({url: `/pages/home`,openType: 'reLaunch'})" class="item-child" :style="{background: primaryColor,color:'#fff'}">直接登录</view>
				</view>
				<view class="flex-center abs popup-close" @tap.stop="loginClose">
					<i class="iconfont iconguanbi"></i>
				</view>
			</view>
		</uni-popup>
		
		<!-- <uni-popup ref="show_phone_item" :maskClick="false">
			<view @tap.stop.prevent class="common-popup-content popup-phone pd-lg flex-center flex-column fill-base">
				<view class="f-md-title c-black">请输入手机号</view>
				<view class="space-lg pb-lg"></view>
				<view class="space-lg pb-lg"></view>
				<view class="flex-center mb-lg">
					<view class="input-info sm mr-md radius-16">
						<input v-model="subForm.phone" type="number"
							class="item-input flex-y-center pl-lg pr-lg f-sm-title c-title"
							placeholder-class="c-placeholder" :placeholder="subRule[0].errorMsg" />
					</view>
					<view @tap="getCode(2)" class="send-btn flex-center c-base radius-16"
						:style="{background:primaryColor}">
						{{phoneTime>0?`(${phoneTime}s)`:'发送'}}
					</view>
				</view>
				<view class="input-info radius-16">
					<input v-model="subForm.code" type="number"
						class="item-input flex-y-center pl-lg pr-lg f-sm-title c-title" maxlength="6"
						placeholder-class="c-placeholder" :placeholder="subRule[1].errorMsg" />
				</view>
				<view class="button">
					<view @tap.stop="$refs.show_phone_item.close()" class="item-child">
						取消
					</view>
					<view @tap.stop="submit" class="item-child" :style="{background: primaryColor,color:'#fff'}">
						确定
					</view>
				</view>
			</view>
		</uni-popup> -->
	</view>
</template>

<script>
	import siteInfo from '@/siteinfo.js';
	import {
		mapState,
		mapActions,
		mapMutations
	} from "vuex"
	import pwPopup from '@/components/pw-popup.vue'
	export default {
		components: {
			pwPopup
		},
		data() {
			return {
				coach_phone: '',
				isCheck: false,
				current: 0,
				params: {
					phone: '',
					code: ''
				},
				rule: [{
						name: "phone",
						checkType: "isMobile",
						errorMsg: "请输入手机号",
						regText: "手机号"
					},
					{
						name: "code",
						checkType: "isNotNull",
						errorMsg: "请输入验证码",
						regText: "验证码"
					}
				],
				lockTap: false,
				authTime: 0,
				phoneTime: 0,
				subForm: {
					phone: '',
					code: ''
				},
				subRule: [{
						name: "phone",
						checkType: "isMobile",
						errorMsg: "请输入手机号",
						regText: "手机号"
					},
					{
						name: "code",
						checkType: "isNotNull",
						errorMsg: "请输入验证码",
						regText: "验证码"
					}]
			}
		},
		computed: mapState({
			primaryColor: state => state.config.configInfo.primaryColor,
			subColor: state => state.config.configInfo.subColor,
			configInfo: state => state.config.configInfo,
			userInfo: state => state.user.userInfo,
			location: state => state.user.location,
			isLogin: state => state.user.isLogin,
		}),
		onLoad() {
			//this.getConfigCall()
			this.initIndex()
		},
		methods: {
			...mapActions(['getUserInfo','getConfigInfo']),
			...mapMutations(['updateConfigItem', 'updateUserItem']),
			async initIndex(refresh = false) {
				if(!this.configInfo.id || refresh){
					await this.getConfigInfo({is_coach: 0})
				}
				this.$util.hideAll()
				this.isLoad = true
			},
			confirm() {
				this.$refs.pwpopup.close()
				this.$util.goUrl({
					url: `/login/pages/register`
				})
			},
			navSwitch(index) {
				this.current = index
			},
			async getCode(type = 1){
				console.log(this.params)
				let {
					phone
				} = type == 1 ? this.params : this.subForm
				if (!/^(1[0-9]{10})$/.test(phone)) { //电话号码校验
					this.$util.showToast({
						title: `${phone} 手机号无效`
					})
					return 
				}
				let {
					authTime,
					phoneTime
				} = this
				if (authTime && type == 1) return
				if (phoneTime && type == 2) return
				let time = 60
				let times = 60
				this.timer = setInterval(() => {
					if (time === 0) {
						clearInterval(this.timer)
						return
					}
					time--
					this.authTime = time
				}, 1000)
				this.timers = setInterval(() => {
					if (times === 0) {
						clearInterval(this.timers)
						return
					}
					times --
					this.phoneTime = times
				}, 1000)
				
				await this.$api.base.sendShortMsg({
					phone,
					key: 'coach_login'
				})
				this.$util.showToast({
					title: `验证码发送成功`
				})
			},
			//表单验证
			validate(param , rule) {
				let validate = new this.$util.Validate();
				rule.map(item => {
					let {
						name,
					} = item
					validate.add(param[name], item);
				})
				let message = validate.start();
				return message;
			},
			async toLogin() {
				if (!this.isCheck) return
				let param = this.$util.deepCopy(this.params)
				let rule = this.$util.deepCopy(this.rule)
				let msg = this.validate(param , rule);
				if (msg) {
					this.$util.showToast({
						title: msg
					})
					return
				}
				if (this.lockTap) return
				this.lockTap = true
				this.$util.showLoading()
				
				try {
					// #ifdef APP-PLUS
					let data = await this.$api.base.phoneLoginNew(param)
					
					console.log(data , '========> phoneLogin') 
					let {
						coach_status = 0,
						company_status = 0
					} = data ? data.data : data
					
					if([2,3].includes(coach_status) || [2,3].includes(company_status)){
						this.updateUserItem({
							key: 'isAppLogin',
							val: true
						})
						this.updateUserItem({
							key: 'userInfo',
							val: data.data
						})
						this.updateUserItem({
							key: 'autograph',
							val: data.autograph
						})
						this.$util.hideAll()
						this.lockTap = false
						
						this.$util.showToast({
							title: `登录成功`
						}) 
						this.getConfigInfo()
						setTimeout(()=>{
							this.$util.goUrl({
								url: `/pages/home`,
								openType: 'reLaunch'
							})
						},1000)
					}else if([0,1,4].includes(coach_status) || [0,1,4].includes(company_status)){
						this.$util.hideAll()
						this.lockTap = false
						await this.toAppLogin()
					}else{
						this.$util.hideAll()
						this.lockTap = false
					}
					// #endif
					// #ifdef MP-WEIXIN
					let data = await this.$api.base.phoneLogin(param)
					this.updateUserItem({
						key: 'isAppLogin',
						val: true
					})
					this.updateUserItem({
						key: 'userInfo',
						val: data.data
					})
					this.updateUserItem({
						key: 'autograph',
						val: data.autograph
					})
					this.$util.hideAll()
					this.lockTap = false
					
					this.$util.showToast({
						title: `登录成功`
					}) 
					this.getConfigInfo()
					setTimeout(()=>{
						this.$util.goUrl({
							url: `/pages/home`,
							openType: 'reLaunch'
						})
					},1000)
					// #endif
				} catch (e) {
					setTimeout(() => {
						this.lockTap = false
						this.$util.hideAll()
					}, 2000)
				}
			},
			// APP登录
			async toAppLogin() {
				// this.toConfirmLoginApp()
				// return
				this.$util.showLoading()
				let {
					loginType: provider = 'weixin'
				} = this
			
				try {
					let [providerErr, providerData] = await uni.getProvider({
						service: 'oauth',
					});
					if (providerErr) {
						this.$util.hideAll()
						this.$util.showToast({
							title: providerErr
						})
						this.lockTap = false
						return
					}
					let [loginErr, loginData] = await uni.login({
						provider
					});
					console.log(loginErr, loginData)
					if (loginErr) {
						this.$util.hideAll()
						this.$util.showToast({
							title: loginErr
						})
						this.lockTap = false
						return
					}
					let [infoErr, infoData] = await uni.getUserInfo({
						provider
					})
					if (infoErr) {
						this.$util.hideAll()
						this.$util.showToast({
							title: infoErr
						})
						this.lockTap = false
						return
					}
			
					let {
						userInfo = {}
					} = infoData
					let {
						openId = ''
					} = userInfo
					console.log(userInfo , provider , '=========> ')
					this.$util.hideAll()
					if (!openId) return
					this.$util.showLoading({
						title: "登录中..."
					})
					try {
						let param = {
							type: provider == 'weixin' ? 2 : 3,
							param: {
								data: userInfo
							},
							init: 1
						}
						this.toConfirmLogin(param)
					} catch (e) {
						this.$util.hideAll()
						this.lockTap = false
					}
				} catch (e) {
					this.$util.hideAll()
					this.$util.showToast({
						title: `没有获取到用户信息，请确认已登录`
					});
					this.lockTap = false
				}
			},
			async toConfirmLogin(login_params) {
				let {
					loginType
				} = this
			
				let {
					type,
					param,
					init = 0
				} = login_params
			
				let methodType = {
					1: 'webLogin',
					2: 'appLogin',
					3: 'iosLogin'
				}
			
				let methodModel = methodType[type]
				let user_info = await this.$api.base[methodModel](param)
				if (init == 1) {
					this.updateUserItem({
						key: 'appLogin',
						val: param.data
					})
				}
			
			
				let {
					autograph,
					data
				} = user_info
				console.log(user_info, '======> user_info')
				this.$util.hideAll()
				this.lockTap = false
				
				this.updateUserItem({
					key: 'isShowLogin',
					val: false
				})
				this.updateUserItem({
					key: 'userInfo',
					val: data
				})
				this.updateUserItem({
					key: 'autograph',
					val: autograph
				})
				
				let {
					coach_status = 0,
					company_status = 0,
					coach_phone = ''
				} = data
				this.coach_phone = coach_phone
				
				if([2,3].includes(coach_status) || [2,3].includes(company_status)){
					if(this.params.phone !== coach_phone){
						this.$refs.show_login.open()
						return
					}
					this.$util.goUrl({url: '/pages/home', openType: 'reLaunch'})
					return
				}
				if([1,4].includes(coach_status)){
					this.$util.goUrl({url: `/user/pages/service-apply-new`})
					return
				}
				if([1,4].includes(company_status)){
					this.$util.goUrl({url: `/user/pages/company-apply`})
					return
				}
				if(coach_status == 0 || company_status == 0){
					this.$refs.show_apply.open()
					return
				}
				
				
				this.$util.goUrl({
					url: '/pages/home',
					openType: 'reLaunch'
				})
				
			},
			// 更换手机号
			async replacePhone(){
				if (this.lockTap) return
				this.lockTap = true
				this.$util.showLoading()
				try{
					let data = await this.$api.base.updatePhone({phone: this.params.phone})
					console.log(data, '=========> updatePhone')
					this.$refs.show_login.close()
					this.$util.showToast({
						title: '更换成功'
					})
					setTimeout(()=>{
						this.$util.goUrl({
							url: `/pages/home`,
							openType: 'reLaunch'
						})
						this.lockTap = false
					},1000)
				}catch(e){
					console.log(e, '=========> e')
					setTimeout(() => {
						this.lockTap = false
						this.$util.hideAll()
					}, 2000)
				}
			},
			async toLoginCall(param) {
				console.log(param , '=========> toLoginCall')
				let user_info = await this.$api.login.pwdLogin(param)
				this.updateUserItem({
					key: 'appLogin',
					val: param
				})
				let {
					autograph,
					data
				} = user_info
				this.$util.hideAll()
				this.updateUserItem({
					key: 'userInfo',
					val: data
				})
				this.updateUserItem({
					key: 'autograph',
					val: autograph
				})
				if (!this.configInfo.id) {
					await this.getConfigInfo()
				}
				await this.getUserInfo()
				setTimeout(() => {
					// if(this.isLogin == 1){
					// 	this.$util.goUrl({url:`/pages/service`,	openType: `reLaunch`})
					// }else{
					// 	this.$util.goUrl({url:1,openType:'navigateBack'})
					// }
					this.$util.goUrl({url:`/pages/service`,	openType: `reLaunch`})
				}, 1000)
			},
			loginClose(){
				this.$refs.show_login.close()
				this.updateUserItem({
					key: 'isShowLogin',
					val: false
				})
				this.updateUserItem({
					key: 'userInfo',
					val: {}
				})
				this.updateUserItem({
					key: 'autograph',
					val: ''
				})
			},
			goDetail(type) {
				// this.$util.goUrl({
				// 	url: '/user/pages/agreement?type=' + type
				// })
				let {
					siteroot
				} = siteInfo
				let href = siteroot.split('index.php')[0]
				let page = type == 1 ? 'protocol' : 'information'
				let url = `${href}${page}.html`
				this.$util.goUrl({
					url,
					openType: 'web'
				})
			},
			toUrl(type){
				if(type == 1){
					this.$util.goUrl({url: `/user/pages/company-apply`})
				}else{
					this.$util.goUrl({url: `/user/pages/service-apply-new`})
				}
				this.$refs.show_apply.close()
			},
			// async getConfigCall() {
			// 	let data = await this.$api.login.getConfig()
			// 	this.login_info = data
			// 	let configInfo = Object.assign(this.$util.deepCopy(this.configInfo), data)
			// 	this.updateConfigItem({
			// 		key: 'configInfo',
			// 		val: configInfo
			// 	})
			// }
		}
	}
</script>

<style lang="scss">
	page {
		background-color: #fff;
	}

	.two-box {
		padding: 0 60rpx;

		.box-header {
			padding-top: 70rpx;
			padding-bottom: 70rpx;

			.nav-line {
				width: 50rpx;
				height: 4px;
				left: 50%;
				bottom: -10px;
				transform: translate(-50%, 0);
				border-radius: 4px;
			}
		}

		.box-item {
			height: 140rpx;
			background-color: #F6F7FB;

			.box-item-left {
				width: 170rpx;
			}

			input {
				line-height: 140rpx;
				height: 140rpx;
			}
		}

		.box-text {
			letter-spacing: 1px;
			line-height: 32rpx;
			color: #6C727F;
		}

		.a-btn {
			height: 110rpx;
			line-height: 110rpx;
		}
		
		.code-btn{
			width: 180rpx;
			height: 70rpx;
		}
		
	}
	
	.popup-phone {
		width: 630rpx;
	
		.input-info {
			width: 570rpx;
			height: 90rpx;
			background: #F7F7F7;
	
			.item-input {
				height: 90rpx;
				font-size: 32rpx;
				text-align: left;
			}
		}
	
		.input-info.sm {
			width: 400rpx;
		}
	
		.send-btn {
			width: 150rpx;
			height: 90rpx;
		}
	}
	
	.popup-close{
		right: 30rpx;
		top: 30rpx;
	}
</style>
